<template>
  <div class="screen-container">
    <!--主地图-->
    <div id="mainMap" class="main-map"></div>

    <SearchShip class="search-ship" :filter="shipFilter" @select="doSearchLocateShip"></SearchShip>

    <WarnShipList
      ref="warnshipListRef"
      class="warn-shiplist"
      :only-show-warn-ship.sync="onlyShowWarnShip"
      @on-expanded="warnShipListExpanded"
      @ship-click="warnShipClick"
    ></WarnShipList>

    <!--时间信息框-->
    <TimeBox class="time-box-panel"></TimeBox>

    <!--全屏-->
    <div class="btn-fullscreen" @click="doFullScreen">
      <span :class="['iconfont', isFullscreen ? 'icon-exit-fullscreen' : 'icon-fullscreen']"></span>
    </div>

    <!--放大缩小地图工具条-->
    <MainToolset class="main-toolset" :tool-list="mainToolList" @toolClick="mainToolClick"></MainToolset>

    <!--放大缩小地图工具条-->
    <div class="map-toolset">
      <div class="map-tool" @click="mapZoomIn">
        <span class="el-icon-plus" :class="isMapMaxZoom ? 'zoom-disable' : ''"></span>
      </div>
      <div class="map-tool" @click="mapZoomOut">
        <span class="el-icon-minus" :class="isMapMinZoom ? 'zoom-disable' : ''"></span>
      </div>
    </div>
    <!--鼠标位置经纬度坐标-->
    <div v-show="mouseLat" class="map-mouse-coord">
      <span>{{ mouseLat }}</span>
      <span>{{ mouseLng }}</span>
    </div>

    <!--地图切换-->
    <TileLayerSwitcher :main-map="mainMap" class="map-switch"> </TileLayerSwitcher>

    <DraggableDialog :visible.sync="shipListDialogShow" width="450px" left="20px" top="110px" :draggable="false">
      <ShipListModal :ship-list="shipList" @ship-click="warnShipClick"></ShipListModal>
    </DraggableDialog>

    <DraggableDialog :visible.sync="shipDetailDialogShow" width="450px" left="20px" top="110px" :draggable="true">
      <!-- <span>测试内容</span> -->
      <ShipDetail
        :ship-info="currentShip"
        :current-voyage="currentVoyage"
        @btn-click="shipDetailBtnClick"
        @update-voyage-info="updateVoyageData"
      ></ShipDetail>
      <!-- <div slot="footer">
        <el-button @click="shipDetailDialogShow = false">取 消</el-button>
        <el-button type="primary" @click="shipDetailDialogShow = false">确 定</el-button>
      </div> -->
    </DraggableDialog>

    <DraggableDialog :title="voyageNumDialogTitle" :visible.sync="voyageNumDialogShow" width="531px" left="480px" top="110px" :draggable="true">
      <VoyageNum :voyage-info="currentVoyage"></VoyageNum>
    </DraggableDialog>

    <DraggableDialog title="短报文" :visible.sync="shortMsgDialogShow" width="531px" left="480px" top="110px" :draggable="true">
      <ShortMessage :ship-info="currentShip"></ShortMessage>
    </DraggableDialog>

    <DraggableDialog title="查看轨迹" :visible.sync="shipHisSearchDialogShow" width="445px" left="480px" top="110px" :draggable="true">
      <ShipHisSearchSetting @ok="shipHisSearchOk" @cancel="shipHisSearchCancel"></ShipHisSearchSetting>
    </DraggableDialog>

    <DraggableDialog title="告警消息" :visible.sync="warnMessageShow" width="417px" left="480px" top="110px" :draggable="true">
      <WarnMessage :ship-info="currentShip"></WarnMessage>
    </DraggableDialog>

    <DraggableDialog title="实时工况" :visible.sync="realtimeWorkShow" width="500px" left="480px" top="110px" :draggable="true">
      <RealtimeWorkStatus></RealtimeWorkStatus>
    </DraggableDialog>

    <DraggableDialog title="数据统计" :visible.sync="statisticsModalShow" width="530px" left="480px" top="110px" :draggable="true">
      <DataStatistics :ship-info="currentShip"></DataStatistics>
    </DraggableDialog>
    <DraggableDialog title="动态快报" :visible.sync="dynamicReportShow" width="500px" left="480px" top="110px" :draggable="true">
      <DynamicReport :ship-info="currentShip"></DynamicReport>
    </DraggableDialog>

    <MiniDrawer title="筛选船舶" :visible.sync="filterShipDrawerShow" direction="rtl" top="110px" right="60px" size="300px">
      <!-- <span style="color: #cccccc">筛选船舶!</span> -->
      <ShipFilter @filter-change="shipFilterChanged"></ShipFilter>
    </MiniDrawer>

    <MiniDrawer
      title="坐标定位"
      :visible.sync="locatePointDrawerShow"
      direction="rtl"
      top="203px"
      right="60px"
      size="333px"
      @close="removeLocateFlag"
    >
      <LocationPoint @confirm="doLocatePoint"></LocationPoint>
    </MiniDrawer>
    <MiniDrawer
      title="水域"
      :visible.sync="waterAreaDrawerShow"
      direction="rtl"
      top="296px"
      right="60px"
      size="333px"
      @close="handleWaterAreaDrawerClose"
    >
      <WaterArea ref="waterAreaRef" :main-map="mainMap" @locate-area="handleLocateWaterArea"></WaterArea>
    </MiniDrawer>
    <!-- 暂时用下 -->
    <el-dialog
      title="轨迹"
      :visible.sync="dialogVisible"
      width="350px"
      style="left: 75% !important; top: 1% !important"
      :modal="false"
      :before-close="handleClose"
    >
      <div class="track-time-line">
        <el-timeline>
          <el-timeline-item v-for="(activity, index) in activities" :key="index" color="#004aaa" :timestamp="activity.times">
            <div>速度：{{ activity.speed }} 节</div>
            <div>航向：{{ activity.speed }} °</div>
            <div>
              经度：{{ Math.abs(Util.degreeToDM(activity.longitude, 2)[0]) + '°' + Util.degreeToDM(activity.longitude, 2)[1] + '′' }}
              {{ Util.degreeToDM(activity.longitude, 2)[0] > 0 ? 'E' : 'W' }}
            </div>
            <div>
              纬度：{{ Math.abs(Util.degreeToDM(activity.latitude, 2)[0]) + '°' + Util.degreeToDM(activity.latitude, 2)[1] + '′' }}
              {{ activity.latitude && (activity.latitude > 0 ? 'N' : 'S') }}
            </div>
            <div>来源：{{ activity.org }}</div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import myShipIcon from "@/assets/images/datascreen/ship-my.png";
// import otherShipIcon from "@/assets/images/datascreen/ship-other.png";
import { myShipIcon, otherShipIcon, locatePointIcon } from '@/utils/map/MapIcons'
import { createNamespacedHelpers } from 'vuex'
import screenfull from 'screenfull'
import DraggableDialog from '@/components/draggable-dialog'
import MiniDrawer from '@/components/mini-drawer'
import TimeBox from './components/TimeBox.vue'
import MainToolset from './components/MainToolset.vue'
import LocationPoint from './components/LocationPoint.vue'
import ShipFilter from './components/ShipFilter.vue'

import SearchShip from './components/SearchShip.vue'
import WarnShipList from './components/WarnShipList.vue'
import ShipDetail from './components/ShipDetail.vue'
import VoyageNum from './components/VoyageNum.vue'
import ShortMessage from './components/ShortMessage.vue'
import ShipHisSearchSetting from './components/ShipHisSearchSetting.vue'

import WarnMessage from './components/WarnMessage.vue'
import DataStatistics from './components/DataStatistics.vue'
import DynamicReport from './components/DynamicReport.vue'
import ShipListModal from './components/ShipListModal.vue'
import RealtimeWorkStatus from './components/RealtimeWorkStatus.vue'
import TileLayerSwitcher from './components/TileLayerSwitcher.vue'
import WaterArea from './components/WaterArea.vue'

import WebSocketCreator from '@/utils/WebSocketCreator'
import {
  getShipVoyageInfo,
  getLastStatusByShipId,
  getCurrentShipVoyageInfo,
  getShipVoyageHis,
  getShipLocationHis,
  getShipLocationDetail,
  queryShipLocations
} from '@/api/ship'
import { cancelShipFavor } from '@/api/shipGroup'
import { getDict } from '@/api/dict'
import { L, MainMap, BoatManager, ShipLocationLayer, TrackLayer, ScaleNautic, Measure, Util, GeoUtil } from '@haiking/haiking-map'
import '@haiking/haiking-map/dist/haiking-map.min.css'
import { setTiandituMap } from '@/utils/map/MapConfig'
setTiandituMap(MainMap)
const { mapState } = createNamespacedHelpers('user')
// MainMap.setMapConfig({
//   tianditu: {
//     vecLayerUrl: `http://{s}.tianditu.gov.cn/DataServer?T=vec_c&x={x}&y={y}&l={z}&tk=7b1a5dba6a33168a0de923da256afd9a`, // 天地图街道切片图层url
//     vecLayerParams: {
//       subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
//       zoomOffset: 1,
//     },

//     cvaLayerUrl: `http://{s}.tianditu.gov.cn/DataServer?T=cva_c&x={x}&y={y}&l={z}&tk=7b1a5dba6a33168a0de923da256afd9a`, // 天地图注记切片图层url
//     cvaLayerParams: {
//       subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
//       zoomOffset: 1,
//     },
//   },
// });

export default {
  components: {
    DraggableDialog,
    MiniDrawer,
    TimeBox,
    MainToolset,
    LocationPoint,
    ShipFilter,
    SearchShip,
    WarnShipList,
    ShipDetail,
    VoyageNum,
    ShortMessage,
    ShipHisSearchSetting,

    WarnMessage,
    DataStatistics,
    DynamicReport,
    ShipListModal,
    RealtimeWorkStatus,
    TileLayerSwitcher,
    WaterArea
  },
  data() {
    return {
      dialogVisible: false,
      Util,
      activities: [
        {
          org: '移动网络',
          longitude: '120.67966',
          latitude: '32.05706',
          speed: '0.0',
          course: '0.0',
          time: '2023-05-17 08:04:12'
        },
        {
          org: '移动网络',
          longitude: '120.67966',
          latitude: '32.05706',
          speed: '0.0',
          course: '0.0',
          time: '2023-05-17 08:19:12'
        },
        {
          org: '卫星',
          longitude: '120.67966',
          latitude: '32.05706',
          speed: '0.0',
          course: '0.0',
          time: '2023-05-17 08:49:12'
        },
        {
          org: '移动网络',
          longitude: '120.67966',
          latitude: '32.05706',
          speed: '0.0',
          course: '0.0',
          time: '2023-05-17 09:09:02'
        },
        {
          org: '移动网络',
          longitude: '120.67966',
          latitude: '32.05706',
          speed: '0.0',
          course: '0.0',
          time: '2023-05-17 09:29:22'
        },
        {
          org: '移动网络',
          longitude: '120.67966',
          latitude: '32.05706',
          speed: '0.0',
          course: '0.0',
          time: '2023-05-17 09:29:22'
        },
        {
          org: '移动网络',
          longitude: '120.67966',
          latitude: '32.05706',
          speed: '0.0',
          course: '0.0',
          time: '2023-05-17 09:29:22'
        },
        {
          org: '移动网络',
          longitude: '120.67966',
          latitude: '32.05706',
          speed: '0.0',
          course: '0.0',
          time: '2023-05-17 09:29:22'
        },
        {
          org: '移动网络',
          longitude: '120.67966',
          latitude: '32.05706',
          speed: '0.0',
          course: '0.0',
          time: '2023-05-17 09:29:22'
        },
        {
          org: '卫星',
          longitude: '120.67966',
          latitude: '32.05706',
          speed: '0.0',
          course: '0.0',
          time: '2023-05-17 09:29:22'
        },
        {
          org: '移动网络',
          longitude: '120.67966',
          latitude: '32.05706',
          speed: '0.0',
          course: '0.0',
          time: '2023-05-17 09:29:22'
        },
        {
          org: '移动网络',
          longitude: '120.67966',
          latitude: '32.05706',
          speed: '0.0',
          course: '0.0',
          time: '2023-05-17 09:29:22'
        }
      ],
      // tenantId: "1557612610958585857",
      shipList: [],
      //myShipIds: [],
      isFullscreen: false,
      webSocket: undefined,
      shipLayer: undefined,
      waterAreaLayer: undefined,
      mainMap: undefined,
      locateFlagMarker: undefined,
      measureTool: undefined,
      shipMapLevel: 8,

      onlyShowWarnShip: false,

      // 弹框
      shipListDialogShow: false,
      shipDetailDialogShow: false,
      voyageNumDialogShow: false,
      voyageNumDialogTitle: '当前航次-航次号：',
      shortMsgDialogShow: false,
      shipHisSearchDialogShow: false,
      addFavorDialogShow: false,
      warnMessageShow: false,
      statisticsModalShow: false,
      dynamicReportShow: false,
      realtimeWorkShow: false,

      // 主工具条抽屉
      favorShipDrawerShow: false,
      filterShipDrawerShow: false,
      measureDisDrawerShow: false,
      locatePointDrawerShow: false,
      waterAreaDrawerShow: false,

      // 鼠标经纬度
      mouseLng: '',
      mouseLat: '',

      // 主工具条工具配置
      mainToolList: [
        // {
        //   toolKey: "favor-ship",
        //   toolName: "关注",
        //   toolIconClass: "iconfont icon-rate",
        // },
        {
          toolKey: 'filter-ship',
          toolName: '筛选',
          toolIconClass: 'iconfont icon-filter'
        },
        {
          toolKey: 'measure-dis',
          toolName: '测距',
          toolIconClass: 'iconfont icon-measure'
        },
        {
          toolKey: 'locate-point',
          toolName: '定位',
          toolIconClass: 'iconfont icon-locate'
        },
        {
          toolKey: 'water-area',
          toolName: '水域',
          toolIconClass: 'iconfont icon-crm-center'
        }
      ],

      // 船舶数据
      currentShip: {
        tenantId: '1593133915812065282',
        shipId: '1593134439886155778',
        isFavor: false
      },
      currentVoyage: {},

      shipFilter: undefined,
      favorShips: [],

      selectedShipInterval: null,

      mapMinZoom: 3,
      mapMaxZoom: 18,
      currentMapZoom: 3
    }
  },
  computed: {
    ...mapState(['tenantId']),
    isMapMinZoom() {
      return this.currentMapZoom === this.mapMinZoom
    },
    isMapMaxZoom() {
      return this.currentMapZoom === this.mapMaxZoom
    }
  },
  created() {
    this.activities.map((val, index) => {
      const timeArray = this.$utils.parseTime(new Date(), '{y}/{m}/{d} {h}:{i}:{s}').split(' ')
      this.yearMonth = timeArray[0]
      this.currentTime = timeArray[1]
      val.times =
        this.yearMonth +
        ' ' +
        this.$moment()
          .subtract('minute', (Math.random() + index) * 20)
          .format('HH:mm:ss')
      // val.times = this.$moment.startOf('week');
      // console.log("🤡 ~  val.times:",this.$moment().add('minute',9).format('HH:mm:ss'))
    })
  },
  watch: {
    onlyShowWarnShip: function (val, oldVal) {
      // 重新加载船舶数据
      if (this.shipLayer) {
        this.shipLayer.reloadShipData()
      }
    },
    shipHisSearchDialogShow: function (val, oldVal) {
      if (this.trackLayer && val === false) {
        this.trackLayer.clearTrack()
      }
    },
    shipDetailDialogShow: function (val, oldVal) {
      if (val === false) {
        this.closeShipDetailSubDialog() // 关闭船舶详情的所有二级弹框
      } else {
        this.unExpandMyShipList()
      }
    }
  },
  mounted() {
    this.updateShipFilter()
    this.initData()
    this.initMap()
    this.initSocket()

    // 大屏全屏处理
    if (screenfull.isEnabled) {
      screenfull.on('change', () => {
        this.isFullscreen = screenfull.isFullscreen
      })

      // f11按键全屏特殊处理
      // 监听按键事件
      window.addEventListener(
        'keydown',
        (event) => {
          if (event.keyCode === 122) {
            // 禁用f11
            event.returnValue = false
            // 全屏
            this.doFullScreen()
          }
        },
        true
      )
    }
  },
  destroyed() {
    if (this.shipLayer) {
      this.shipLayer.destroy()
    }

    if (this.selectedShipInterval) {
      clearInterval(this.selectedShipInterval)
    }
  },
  methods: {
    handleClose() {
      this.dialogVisible = false
    },
    // 更新全局船舶筛选条件
    async updateShipFilter() {
      const shipTypeFilter = await this.$store.dispatch('shipfilter/getShipTypeFilter')

      const shipLengthFilter = await this.$store.dispatch('shipfilter/getShipLengthFilter')
      const shipLengths = []
      if (shipLengthFilter.custom) {
        shipLengths.push({
          lengthMin: shipLengthFilter.customMin,
          lengthMax: shipLengthFilter.customMax
        })
      } else {
        this.$store.state.shipfilter.shipLengthList.forEach((element) => {
          if (shipLengthFilter.lengths.includes(element.code)) {
            let minMax
            if (element.label.includes('>')) {
              minMax = element.label.split('>')
              shipLengths.push({
                lengthMin: parseInt(minMax[1])
              })
            } else {
              minMax = element.label.split('-')
              shipLengths.push({
                lengthMin: parseInt(minMax[0]),
                lengthMax: parseInt(minMax[1])
              })
            }
          }
        })
      }

      const shipStatusFilter = await this.$store.dispatch('shipfilter/getShipStatusFilter')
      const filter = {
        shipTypeList: shipTypeFilter,
        lengthRangeList: shipLengths,
        statusList: shipStatusFilter
      }
      this.shipFilter = filter
    },
    // 船舶筛选条件发生变化
    async shipFilterChanged() {
      await this.updateShipFilter()
      // 重新加载船舶数据
      if (this.shipLayer) {
        this.shipLayer.reloadShipData()
      }
    },
    // 初始化数据
    async initData() {
      this.currentShip.tenantId = this.tenantId
    },
    // 初始化地图
    initMap() {
      const mainMap = (this.mainMap = new MainMap('mainMap', {
        minZoom: this.mapMinZoom, // 3,
        maxZoom: this.mapMaxZoom, // 18,
        center: [33.333, 120.098],
        zoom: 3,
        //showChannelMap: true,
        scaleControl: false,
        worldCopyJump: true,
        showImageMap: true,
        defaultMap: MainMap.mapType.BASE_MAP
        // 地图范围限制
        // maxBounds: [
        //   [-90, -180],
        //   [90, 180],
        // ],
        // maxBoundsViscosity: 1,
      }))

      // 自定义航道图图层
      const channelLayer = this.mainMap.createTileLayer(
        'https://tiandimap.ixunhang.com/tiandi-map/map/getHangdaoMap?tilematrix={z}&tilerow={y}&tilecol={x}'
      )
      this.mainMap.customChannelMap(channelLayer)

      const scaleNautic = new ScaleNautic({
        metric: false,
        imperial: false,
        nautic: true
      })
      mainMap.addControl(scaleNautic)

      mainMap.map.on('mousemove', this.updateMouseCoord, this) // 添加鼠标移动监听

      mainMap.map.on('zoomend', (e) => {
        this.currentMapZoom = mainMap.map.getZoom()
      })

      this.measureTool = new Measure(mainMap, {
        unitSystem: 'nautic',
        showAzimut: true,
        color: '#4C4C4C'
      })

      this.waterAreaLayer = L.geoJSON(
        { type: 'FeatureCollection', features: [] },
        {
          style: function (feature) {
            return { color: 'red' }
          }
        }
      )
        .bindPopup(function (layer) {
          return `
            <div">
              <div>${layer.feature.properties.name}${layer.feature.properties.remark ? '（' + layer.feature.properties.remark + '）' : ''} </div>

            </div>
          `
        })
        .addTo(mainMap.map)

      this.trackLayer = new TrackLayer(mainMap, {
        lngField: 'longitude',
        latField: 'latitude',
        toolTipHtml: (data) => {
          const lngDM = Util.degreeToDM(data.longitude, 2)
          const latDM = Util.degreeToDM(data.latitude, 2)
          const lngFlag = lngDM[0] > 0 ? 'E' : 'W'
          const latFlag = latDM[0] > 0 ? 'N' : 'S'
          return `<div>
              <div></div>
              <div>速度：${data.speed}节</div>
              <div>航向：${data.course}°</div>
              <div>时间：${data.time}</div>
              <div>经度：${Math.abs(lngDM[0]) + '°' + lngDM[1] + '′'}${lngFlag}</div>
              <div>纬度：${Math.abs(latDM[0]) + '°' + latDM[1] + '′'}${latFlag}</div>
              <div>信源：${data.source == 1 ? '移动网络' : data.source == 2 ? '卫星' : ''}
              </div>
            </div>`
        },
        labelFunc: (data) => {
          return data.time
        }
      })

      this.shipLayer = new ShipLocationLayer(mainMap, {
        // minZoom: 1,
        labelMinZoom: 1,
        shipkeyField: 'shipId',
        shipLabelField: 'shipName',
        lonField: 'longitude',
        latField: 'latitude',
        updateInterval: 20000,
        // selectSizeFormatter: () => {
        //   return [50, 50];
        // },
        // 船舶样式转换，此处具体到业务根据实际情况，给定不同的图标或设置boatSimple的不同颜色
        // boatStyle: (boatInfo) => {
        //   if (boatInfo.tenantId === this.tenantId) {
        //     return L.icon({
        //       iconUrl: myShipIcon,
        //       iconSize: [17, 50],
        //       iconAnchor: [8.5, 25],
        //     });
        //   } else {
        //     return L.icon({
        //       iconUrl: otherShipIcon,
        //       iconSize: [14, 50],
        //       iconAnchor: [7, 25],
        //     });
        //   }
        // },
        // boatStyle: (boatInfo, width, height) => {
        //   return ImgIcons.greenBoat();
        // },
        shipClick: (e) => {
          if (this.$refs.boatInfoDialog) {
            this.$refs.boatInfoDialog.style.left = e.originalEvent.clientX + 30 + 'px'
            this.$refs.boatInfoDialog.style.top = e.originalEvent.clientY - 30 + 'px'
          }
          const shipInfo = e.target.props
          let isFavor = false
          if (this.favorShips.includes(shipInfo.shipId)) {
            isFavor = true
          }
          this.currentShip = { ...shipInfo, isFavor: isFavor }
          this.showShipDetailInfo()

          // if (e.target.props.mmsi == "413555680") {
          //   this.dialogVisible = true;
          // }

          // if (boatInfo && boatInfo.tenantId === this.tenantId) {
          //   const boatSelect = this.shipList.find((item) => {
          //     return item.id === boatInfo.shipId;
          //   });
          //   this.currentShip = boatInfo;
          //   console.log(boatInfo);
          //   this.showShipDetailInfo(boatSelect, true, true);
          // }
        },
        onReadyToUpdateShip: (mapBoundBBox) => {
          const zoom = this.mainMap.map.getZoom()
          const mapBound = mapBoundBBox.split(',')
          let param
          if (zoom < 13) {
            param = {
              type: 'all',
              bbox: mapBoundBBox,
              ...this.shipFilter
            }
          } else {
            param = {
              type: 'range',
              lngMin: mapBound[0],
              lngMax: mapBound[2],
              latMin: mapBound[1],
              latMax: mapBound[3],
              bbox: mapBoundBBox,
              ...this.shipFilter
            }
          }
          param.superviseTenantId = this.tenantId
          // const param = {
          //   type: "range",
          //   lngMin: mapBound[0],
          //   lngMax: mapBound[2],
          //   latMin: mapBound[1],
          //   latMax: mapBound[3],
          //   bbox: mapBoundBBox,
          //   ...this.shipFilter,
          // };
          // 只看告警船舶
          if (this.onlyShowWarnShip) {
            //param.tenantId = this.tenantId;
            param.warningFlag = true
          }
          if (this.webSocket) {
            this.webSocket.send(JSON.stringify(param))
          }
        }
      })

      // 30秒刷新一次选中的船舶数据
      this.selectedShipInterval = setInterval(() => {
        this.updateSelectedShip()
      }, 1000 * 30)

      // 地图定位到本公司船舶范围
      // this.locateToMyShips();
    },
    // 初始化websocket
    initSocket() {
      const tokenPrefix = this.$auth.getTokenPrefix()
      const token = this.$auth.getToken()
      if (token) {
        const host = location.host
        let wsProtocol = 'wss:'
        if (location.protocol === 'http:') {
          wsProtocol = 'ws:'
        }
        // const url = `${wsProtocol}//jjy.test.ixunhang.com/gisws/sturgeon/transmission/websocket/${tokenPrefix} ${token}`;
        const url = `${wsProtocol}//${host}/gisws/sturgeon/transmission/websocket/${tokenPrefix} ${token}`
        this.webSocket = new WebSocketCreator({
          websocketUrl: url,
          onopen: () => {
            // 立即定位船舶
            if (this.shipLayer) {
              this.shipLayer.reloadShipData()
            }
          },
          onmessage: (e) => {
            try {
              // token 失效重新登录
              if (e.data == 'tokenInvalid') {
                this.$store.dispatch('user/FedLogOut')
                window.location.reload()
                return
              }
              if (e.data != 'heartbeat') {
                const result = JSON.parse(e.data)

                // 测试多个点的默认显示地图范围
                // const aaa = { ...result.locationStandardList[0] };
                // aaa.longitude = parseFloat(aaa.longitude) + 2;
                // aaa.latitude = parseFloat(aaa.latitude) + 3;
                // aaa.shipId = aaa.shipId + "12121";
                // aaa.shipName = "12121";
                // result.locationStandardList = [...result.locationStandardList];
                // result.locationStandardList.push(aaa);
                // result.locationStandardList[0].shipId = "1562311165254234114";
                if (result && result.bbox) {
                  if (this.shipLayer) {
                    this.shipLayer.updateShipData(result.bbox, result.locationStandardList)
                  }
                }
              }
            } catch (error) {
              console.log(error)
            }
          }
        })
      }
    },
    // 定位到本公司的所有船舶
    locateToMyShips() {
      if (!this.tenantId) {
        return
      }

      if (this.isSearchLocate) {
        return
      }

      queryShipLocations({
        type: 'all',
        tenantId: this.tenantId
      }).then((res) => {
        const ships =
          res.result && res.result.locationStandardList && res.result.locationStandardList.length > 0 ? res.result.locationStandardList : []
        const latLons = []
        ships.forEach((ship) => {
          if (ship.longitude || ship.longitude == 0) {
            latLons.push([ship.latitude, ship.longitude])
          }
        })
        if (latLons.length > 0 && this.mainMap) {
          this.mainMap.map.fitBounds(latLons)
        }
      })
    },
    unExpandMyShipList() {
      if (this.$refs.warnshipListRef) {
        // this.$refs.warnshipListRef.unExpandMyShipList();
      }
    },
    // 关闭船舶详情的所有二级弹框
    closeShipDetailSubDialog() {
      this.voyageNumDialogShow = false
      this.shortMsgDialogShow = false
      this.shipHisSearchDialogShow = false
      this.addFavorDialogShow = false
    },
    // 展开我的船舶列表
    warnShipListExpanded(shipList) {
      this.shipList = shipList || []
      this.shipListDialogShow = true
      this.shipDetailDialogShow = false // 关闭船舶详情弹框
    },
    // 更新选中的船舶数据
    updateSelectedShip() {
      if (this.shipLayer) {
        const selectedShip = this.shipLayer.getSelectedShip()
        if (selectedShip) {
          getShipLocationDetail({
            shipId: selectedShip.shipId
          }).then((res) => {
            if (res.result) {
              this.shipLayer.updateSelectedShip(res.result)
            }
          })
        }
      }
    },

    // 设置地图范围到当前租户的船舶（已经定位的船舶）范围
    setMapViewToTenantShips(shipGpsList) {
      if (shipGpsList && shipGpsList.length > 0) {
        const lonLats = shipGpsList.map((item) => {
          return [item.latitude, item.longitude]
        })
        this.mainMap.map.fitBounds(lonLats)
        const mapZoom = this.mainMap.map.getZoom()

        if (mapZoom > this.shipMapLevel) {
          this.mainMap.map.setZoom(this.shipMapLevel)
        }
        // if (!this.mainMap.map.getBounds().contains(L.latLngBounds(lonLats))) {

        // }

        // this.mainMap.map.fitBounds(lonLats);
      }
    },

    showShipDetailInfo() {
      this.shipDetailDialogShow = true
      this.shipListDialogShow = false // 关闭原船舶列表的弹窗
      this.closeShipDetailSubDialog()
    },
    // 全屏
    doFullScreen() {
      if (screenfull.isEnabled) {
        if (this.isFullscreen) {
          screenfull.exit()
        } else {
          screenfull.request()
        }
      } else {
        // Ignore or do something else
      }
    },

    // 地图放大
    mapZoomIn() {
      if (this.mainMap) {
        const map = this.mainMap.map
        map.zoomIn()
      }
    },

    // 地图缩小
    mapZoomOut() {
      if (this.mainMap) {
        const map = this.mainMap.map
        map.zoomOut()
      }
    },
    // 更新鼠标移动的 地图坐标
    updateMouseCoord(e) {
      const latLng = e.latlng.wrap() // 解决经度大于180或小于-180的问题
      const lngDM = Util.degreeToDM(latLng.lng, 4)
      const latDM = Util.degreeToDM(latLng.lat, 4)
      const lngFlag = lngDM[0] > 0 ? 'E' : 'W'
      const latFlag = latDM[0] > 0 ? 'N' : 'S'

      // 32°5.226N 118°43.775
      this.mouseLng = `${Math.abs(lngDM[0])}° ${lngDM[1]} ${lngFlag}`
      this.mouseLat = `${Math.abs(latDM[0])}° ${latDM[1]} ${latFlag}`
      // this.getContainer().innerHTML = `${latLng.lng.toFixed(
      //   this.options.precision
      // )}&nbsp;&nbsp;${latLng.lat.toFixed(this.options.precision)}`;
    },
    // 主工具条工具点击，切换抽屉组件
    switchMainToolDrawer(toolKey) {
      this.favorShipDrawerShow = toolKey === 'favor-ship'
      this.filterShipDrawerShow = toolKey === 'filter-ship'
      this.locatePointDrawerShow = toolKey === 'locate-point'
      this.waterAreaDrawerShow = toolKey === 'water-area'

      // switch (toolKey) {
      //   case "favor-ship":
      //     this.favorShipDrawerShow = true;
      //     this.filterShipDrawerShow = false;
      //     this.locatePointDrawerShow = false;
      //     break;
      //   case "filter-ship":
      //     this.favorShipDrawerShow = false;
      //     this.filterShipDrawerShow = true;
      //     this.locatePointDrawerShow = false;
      //     break;

      //   case "measure-dis":
      //     this.favorShipDrawerShow = true;
      //     this.filterShipDrawerShow = false;
      //     this.locatePointDrawerShow = false;
      //     break;

      //   case "locate-point":
      //     this.favorShipDrawerShow = true;
      //     this.filterShipDrawerShow = false;
      //     this.locatePointDrawerShow = false;
      //     break;

      //   default:
      //     break;
      // }
    },
    // 主工具条工具按钮点击
    mainToolClick(tool) {
      this.switchMainToolDrawer(tool.toolKey)
      if (tool.toolKey === 'measure-dis') {
        if (this.measureTool) {
          this.measureTool.startMeasureDistance() // 开启测量距离
        }
      } else {
        if (this.measureTool) {
          this.measureTool.stopMeasure() // 开启测量距离
        }
      }
    },
    // 删除定位标记
    removeLocateFlag() {
      if (this.locateFlagMarker) {
        this.locateFlagMarker.removeFrom(this.mainMap.map)
      }
    },
    // 定位点
    doLocatePoint(lngLatObj, lngType, latType) {
      if (lngLatObj) {
        let lng = Util.dmsToDegree(lngLatObj.lngD, lngLatObj.lngM, lngLatObj.lngS, 6)
        let lat = Util.dmsToDegree(lngLatObj.latD, lngLatObj.latM, lngLatObj.latS, 6)

        if (lngType == 'W') {
          lng = -lng
        }

        if (latType == 'S') {
          lat = -lat
        }
        const latLng = [lat, lng]

        if (this.mainMap) {
          this.removeLocateFlag()
          this.locateFlagMarker = L.marker(latLng, {
            icon: L.icon({
              iconUrl: locatePointIcon,
              iconSize: [32, 32]
            })
          })

          this.locateFlagMarker.addTo(this.mainMap.map)
          this.mainMap.locatePoint(latLng, 16)
        }
      }
    },
    // 点击我的船舶
    warnShipClick(shipInfo) {
      this.doLocateShip(shipInfo.shipId)
    },
    // 定位搜索到的船舶
    doSearchLocateShip(item) {
      // if (this.mainMap) {
      //   this.mainMap.locatePoint([item.lat, item.lng], 16);
      // }
      // if (this.shipLayer) {
      //   this.shipLayer.locateShip(item, 17);
      // }
      this.doLocateShip(item.shipId)
    },
    doLocateShip(shipId) {
      getShipLocationDetail({
        tenantId: this.tenantId,
        shipId: shipId
      }).then((res) => {
        if (res.result) {
          if (this.shipLayer) {
            this.shipLayer.locateShip(res.result, 17)

            // 定位选中船舶后显示船舶详情弹框
            const shipInfo = res.result
            let isFavor = false
            if (this.favorShips.includes(shipInfo.shipId)) {
              isFavor = true
            }
            this.currentShip = { ...shipInfo, isFavor: isFavor }
            this.showShipDetailInfo()
          }
        } else {
          this.$message.warning('未查到船舶定位数据！')
        }
      })
    },
    async updateVoyageData() {
      let isSuccess = false
      let voyageData = {}
      if (this.currentShip) {
        this.currentVoyage = {}
        // cargoName: "苹果"
        // cargoType: "水果"
        // cargoWeight: "1000"
        // departurePort: "南宁"
        // destinationPort: "上海"
        // shipLoadStatus: "空载"
        // shipVoyageStatus: "锚泊"
        // voyageNumber: "2022001"
        // voyagePlanEndTime: "--"
        // voyageStartTime: null
        const voyageInfo = await getCurrentShipVoyageInfo(this.currentShip.tenantId, this.currentShip.shipId)
        if (voyageInfo.result) {
          voyageData = voyageInfo.result
          isSuccess = true
        }
        const voyageHis = await getShipVoyageHis(this.currentShip.tenantId, this.currentShip.shipId)
        if (voyageHis.result) {
          voyageData.voyageHisList = voyageHis.result
        }
      }
      this.currentVoyage = voyageData
      this.currentVoyage && this.currentVoyage.voyageNumber && (this.voyageNumDialogTitle = '当前航次-航次号：' + this.currentVoyage.voyageNumber)

      return isSuccess
    },

    async shipDetailBtnClick(btnCode) {
      switch (btnCode) {
        case 'gz':
          this.addFavorDialogShow = true
          this.voyageNumDialogShow = false
          this.shipHisSearchDialogShow = false
          this.shortMsgDialogShow = false
          break
        // 取消关注
        case 'qxgz':
          this.removeShipFavor(this.currentShip.shipId)
          break
        // 航次
        case 'hc':
          const success = await this.updateVoyageData()
          if (!success) {
            this.$message.warning('当前未查到航次信息！')
            return
          }
          this.closeExcludeModalProp('voyageNumDialogShow')
          this.voyageNumDialogShow = true
          break
        // 轨迹
        case 'gj':
          this.closeExcludeModalProp('shipHisSearchDialogShow')
          this.shipHisSearchDialogShow = true
          break
        // 短报文
        case 'dbw':
          this.closeExcludeModalProp('shortMsgDialogShow')
          this.shortMsgDialogShow = true
          break
        // 船舶档案
        case 'dangan':
          window.open(`/modules/ba/ba/shipInfo/edit?id=${this.currentShip.shipId}&view=true&system=system`, '_blank')
          break
        case 'dynamic-report':
          this.dynamicReportShow = true
          this.closeExcludeModalProp('dynamicReportShow')
          break
        // 船载视频
        case 'shipWarn':
          this.warnMessageShow = true
          this.closeExcludeModalProp('warnMessageShow')
          break
        case 'realtime':
          this.realtimeWorkShow = true
          this.closeExcludeModalProp('realtimeWorkShow')
          break
        // 数据统计
        case 'statistics':
          this.statisticsModalShow = true
          this.closeExcludeModalProp('statisticsModalShow')
          break

        // 船舶详情关闭
        case 'close':
          this.shipListDialogShow = true
          this.shipDetailDialogShow = false // 关闭船舶详情弹框
          break

        default:
          break
      }
    },
    // 关闭其他弹窗
    closeExcludeModalProp(key) {
      const keys = [
        'dynamicReportShow',
        'warnMessageShow',
        'realtimeWorkShow',
        'statisticsModalShow',
        'shortMsgDialogShow',
        'addFavorDialogShow',
        'voyageNumDialogShow',
        'shipHisSearchDialogShow'
      ]

      keys
        .filter((k) => k != key)
        .forEach((k) => {
          this[k] = false
        })
    },
    shipHisSearchCancel() {
      this.shipHisSearchDialogShow = false
    },
    shipHisSearchOk(timeRange) {
      // ?deviceNo=00003&startTime=2022-12-08 deviceNo=00003&startTime=2022-12-08 14:30&endTime=2022-12-10 14:55

      // course: "255"
      // latitude: "32.24632"
      // longitude: "126.3253"
      // speed: "10"
      // time: "2022-12-09 14:45:00"
      getShipLocationHis({
        // deviceNo: "00003", // this.currentShip.deviceNo
        // startTime: "2022-12-08 14:30", // timeRange[0],
        // endTime: "2022-12-10 14:55", // timeRange[1],
        deviceNo: this.currentShip.deviceNo,
        startTime: timeRange[0],
        endTime: timeRange[1]
      }).then((res) => {
        if (res.result && res.result.length) {
          if (this.trackLayer) {
            res.result[1].longitude = parseFloat(res.result[1].longitude) + 0.01
            this.trackLayer.addTrack(res.result, true, this.currentShip.shipId, this.currentShip.shipName)
          }
        } else {
          this.$message.warning('未查询到轨迹数据！')
        }
      })
    },
    closeAddFavorDialog(isOkClose) {
      this.addFavorDialogShow = false
      if (isOkClose) {
        this.currentShip.isFavor = true // 设置为已经关注
        this.updateFavorTree()
      }
    },
    // 当添加关注分组时
    favorGroupAdded() {
      this.updateFavorTree()
    },
    // 更新我的关注数据
    updateFavorTree() {
      if (this.$refs.favorTreeRef) {
        this.$refs.favorTreeRef.loadFavorTree()
      }
    },
    // 取消关注船舶
    removeShipFavor(shipId) {
      this.$confirm('确定不再关注该船舶?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          cancelShipFavor(shipId).then((res) => {
            if (res.success) {
              this.$message.success('取消关注成功！')
              this.currentShip.isFavor = false
              this.updateFavorTree()
            } else {
              this.$message.success('取消关注失败！')
            }
          })
        })
        .catch(() => {})
    },
    favorShipChanged(favorShipIds) {
      this.favorShips = favorShipIds
      if (this.currentShip) {
        if (this.favorShips.includes(this.currentShip.shipId)) {
          this.currentShip.isFavor = true
        } else {
          this.currentShip.isFavor = false
        }
      }
    },
    handleLocateWaterArea(waterArea) {
      const geo = GeoUtil.wktToGeoJson(waterArea.geom)
      if (this.mainMap) {
        this.mainMap.locateGeomByGeojson(geo, 15)
        this.waterAreaLayer &&
          this.waterAreaLayer.clearLayers().addData({
            type: 'Feature',
            properties: {
              name: waterArea.name,
              remark: waterArea.remark
            },
            geometry: geo
          })
      }
    },
    handleWaterAreaDrawerClose() {
      this.waterAreaLayer && this.waterAreaLayer.clearLayers().closePopup()
    }
  }
}
</script>
<style lang="scss">
@import '@/assets/styles/component-style/index.scss';
@import '@/assets/styles/shipping-online/index.scss';
.leaflet-boat-label {
  background: #409effab;
  border: 1px solid #409eff;
  border-radius: 10px;
  color: #fff;
  height: auto !important;
  width: auto !important;
  padding: 2px 6px;
  text-align: center;
  white-space: nowrap;
}
</style>

<style scoped lang="scss">
.track-time-line {
  height: 600px;
  overflow-y: scroll;

  &::-webkit-scrollbar-track-piece {
    background: #ffffff;
  }
  &::-webkit-scrollbar-thumb {
    background: #ebeef5;
    border-radius: 20px;
  }
  &::-webkit-scrollbar {
    width: 4px;
    height: 10px;
  }
}
.screen-container {
  //bordermin-height: 100%;
  height: 100%;
  line-height: normal;
  .main-map {
    // background-color: #000d2f;
    // background-color: #aac6ee;
    width: 100%;
    height: 100%;
  }

  .main-map {
    width: 100%;
    height: 100%;
    z-index: 0;
  }
  .search-ship {
    position: absolute;
    left: 20px;
    top: 10px;
  }
  .warn-shiplist {
    position: absolute;
    left: 20px;
    top: 60px;
  }
  .time-box-panel {
    position: absolute;
    right: 100px;
    top: 10px;
  }
  .btn-fullscreen {
    width: 40px;
    height: 40px;
    background: rgba(62, 62, 62, 0.45);
    box-shadow: 0px 2px 6px 0px rgba(64, 100, 197, 0.35);
    border-radius: 3px;
    top: 10px;
    right: 20px;
    padding: 11px;

    color: #ffffff;
    position: absolute;
    cursor: pointer;

    span {
      font-size: 18px;
    }
  }
  .map-toolset {
    position: absolute;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    padding: 5px;
    background: #ffffff;
    box-shadow: 0px 2px 6px 0px rgba(64, 100, 197, 0.35);
    border-radius: 3px;
    right: 20px;
    bottom: 10px;

    .map-tool {
      cursor: pointer;
      padding: 7px;
      &:first-child {
        border-bottom: 1px dashed #d8d8d8;
      }
      span {
        font-size: 16px;
        color: #333333;
        font-weight: bold;
      }
      .zoom-disable {
        color: #c9c9c9 !important;
      }
    }
  }
  .main-toolset {
    position: absolute;
    right: 20px;
    top: 110px;
  }

  .map-mouse-coord {
    position: absolute;
    z-index: 1000;
    right: 72px;
    bottom: 42px;
    width: 118px;
    height: 48px;
    background: rgba(62, 62, 62, 0.45);
    box-shadow: 0px 2px 6px 0px rgba(64, 100, 197, 0.35);
    border-radius: 3px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: flex-end;
    font-size: 14px;
    padding: 4px 9px 4px 9px;
    white-space: nowrap;
    color: #fff;
  }
  .map-switch {
    position: absolute;
    z-index: 1000;
    right: 72px;
    bottom: 9px;
  }
}
</style>
